'use client'

import { useState } from 'react'

interface ImageSearchResult {
  url: string
  thumb: string
  alt: string
  photographer: string
  photographerUrl: string
  source: string
  prompt: string
}

export default function TestImageSearch() {
  const [storyContent, setStoryContent] = useState('')
  const [ageGroup, setAgeGroup] = useState('6-8')
  const [style, setStyle] = useState('watercolor')
  const [searchResults, setSearchResults] = useState<ImageSearchResult[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const handleSearch = async () => {
    if (!storyContent.trim()) {
      setError('请输入故事内容')
      return
    }

    setLoading(true)
    setError('')
    setSearchResults([])

    try {
      const response = await fetch('/api/search-images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          storyContent,
          ageGroup,
          style,
          type: 'main'
        }),
      })

      const data = await response.json()

      if (data.success) {
        setSearchResults(Array.isArray(data.data) ? data.data : [data.data])
      } else {
        setError(data.error || '搜索失败')
      }
    } catch (error) {
      console.error('图片搜索错误:', error)
      setError('网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const handleComicSearch = async () => {
    if (!storyContent.trim()) {
      setError('请输入故事内容')
      return
    }

    setLoading(true)
    setError('')
    setSearchResults([])

    try {
      const response = await fetch('/api/search-images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          storyContent,
          ageGroup,
          style,
          type: 'comic',
          panelCount: 4
        }),
      })

      const data = await response.json()

      if (data.success) {
        setSearchResults(Array.isArray(data.data) ? data.data : [data.data])
      } else {
        setError(data.error || '搜索失败')
      }
    } catch (error) {
      console.error('漫画搜索错误:', error)
      setError('网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 py-8">
      <div className="max-w-6xl mx-auto px-4">
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-gray-800 mb-4">
            图片搜索测试
          </h1>
          <p className="text-lg text-gray-600">
            测试基于故事内容的智能图片搜索功能
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* 输入区域 */}
          <div className="bg-white rounded-lg shadow-lg p-6">
            <h2 className="text-2xl font-semibold mb-4">搜索参数</h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  故事内容
                </label>
                <textarea
                  value={storyContent}
                  onChange={(e) => setStoryContent(e.target.value)}
                  placeholder="请输入故事内容，系统会自动提取关键词进行图片搜索..."
                  className="w-full h-32 p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    年龄组
                  </label>
                  <select
                    value={ageGroup}
                    onChange={(e) => setAgeGroup(e.target.value)}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  >
                    <option value="3-5">3-5岁</option>
                    <option value="6-8">6-8岁</option>
                    <option value="9-12">9-12岁</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    图片风格
                  </label>
                  <select
                    value={style}
                    onChange={(e) => setStyle(e.target.value)}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  >
                    <option value="watercolor">水彩风格</option>
                    <option value="cartoon">卡通风格</option>
                    <option value="realistic">写实风格</option>
                  </select>
                </div>
              </div>

              <div className="flex space-x-4">
                <button
                  onClick={handleSearch}
                  disabled={loading}
                  className="flex-1 bg-blue-600 text-white py-3 px-6 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {loading ? '搜索中...' : '搜索主插图'}
                </button>
                
                <button
                  onClick={handleComicSearch}
                  disabled={loading}
                  className="flex-1 bg-green-600 text-white py-3 px-6 rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {loading ? '搜索中...' : '搜索漫画'}
                </button>
              </div>

              {error && (
                <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                  <p className="text-red-600">{error}</p>
                </div>
              )}
            </div>
          </div>

          {/* 结果展示区域 */}
          <div className="bg-white rounded-lg shadow-lg p-6">
            <h2 className="text-2xl font-semibold mb-4">搜索结果</h2>
            
            {searchResults.length === 0 ? (
              <div className="text-center py-12">
                <div className="text-gray-400 text-6xl mb-4">🖼️</div>
                <p className="text-gray-500">暂无搜索结果</p>
                <p className="text-sm text-gray-400 mt-2">
                  请输入故事内容并点击搜索按钮
                </p>
              </div>
            ) : (
              <div className="space-y-4">
                {searchResults.map((result, index) => (
                  <div key={index} className="border border-gray-200 rounded-lg p-4">
                    <div className="aspect-video bg-gray-100 rounded-lg overflow-hidden mb-3">
                      <img
                        src={result.url}
                        alt={result.alt}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement
                          target.src = 'https://via.placeholder.com/800x600/87CEEB/FFFFFF?text=Image+Not+Found'
                        }}
                      />
                    </div>
                    
                    <div className="space-y-2">
                      <p className="text-sm text-gray-600">
                        <strong>搜索关键词:</strong> {result.prompt}
                      </p>
                      <p className="text-sm text-gray-600">
                        <strong>图片来源:</strong> {result.source}
                      </p>
                      {result.photographer && (
                        <p className="text-sm text-gray-600">
                          <strong>摄影师:</strong>{' '}
                          <a
                            href={result.photographerUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-blue-600 hover:underline"
                          >
                            {result.photographer}
                          </a>
                        </p>
                      )}
                      {result.panelIndex && (
                        <p className="text-sm text-gray-600">
                          <strong>面板序号:</strong> {result.panelIndex}
                        </p>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* 示例故事 */}
        <div className="mt-8 bg-white rounded-lg shadow-lg p-6">
          <h3 className="text-xl font-semibold mb-4">示例故事</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="border border-gray-200 rounded-lg p-4">
              <h4 className="font-medium mb-2">友谊主题</h4>
              <p className="text-sm text-gray-600">
                小兔子在森林里遇到了一只受伤的小鸟。小兔子立刻跑过去帮助小鸟，给它找来食物和水。小鸟很快就康复了，它们成为了最好的朋友。
              </p>
              <button
                onClick={() => setStoryContent('小兔子在森林里遇到了一只受伤的小鸟。小兔子立刻跑过去帮助小鸟，给它找来食物和水。小鸟很快就康复了，它们成为了最好的朋友。')}
                className="mt-2 text-blue-600 hover:underline text-sm"
              >
                使用此示例
              </button>
            </div>
            
            <div className="border border-gray-200 rounded-lg p-4">
              <h4 className="font-medium mb-2">勇气主题</h4>
              <p className="text-sm text-gray-600">
                小熊一直害怕黑暗，不敢一个人睡觉。妈妈告诉它，勇敢不是不害怕，而是面对害怕的勇气。一天晚上，小熊决定要勇敢起来。
              </p>
              <button
                onClick={() => setStoryContent('小熊一直害怕黑暗，不敢一个人睡觉。妈妈告诉它，勇敢不是不害怕，而是面对害怕的勇气。一天晚上，小熊决定要勇敢起来。')}
                className="mt-2 text-blue-600 hover:underline text-sm"
              >
                使用此示例
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
} 